package com.iemes.controller.workcenter_model;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.NcCodeFormMap;
import com.iemes.entity.NcCodeGroupFormMap;
import com.iemes.entity.NcCodeGroupRelationFormMap;
import com.iemes.entity.NumberRuleFormMap;
import com.iemes.entity.ShiftFormMap;
import com.iemes.entity.UserFormMap;
import com.iemes.entity.UserShiftFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.workcenter_model.ShiftService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;


/**
 * 
 */
@Controller
@RequestMapping("/workcenter_model/shift/")
public class ShiftController extends BaseController {
	
	@Inject
	private BaseMapper baseMapper;
		
	@Inject
	private ShiftService shiftService;
	
	private Logger log = Logger.getLogger(this.getClass());
	private String shiftMaintenanceUrl = Common.BACKGROUND_PATH + "/workcenter_model/shift/shift_maintenance";
	private String uDefinedDataType = "shift";

	//页面跳转
	@RequestMapping("shift_maintenance")
	public String Get_shift_maintenance_Url(Model model,HttpServletRequest request) throws Exception {
		model.addAttribute("res", findByRes());
		model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
		String siteId = ShiroSecurityHelper.getSiteId();
		getShiftUserBindData(model, siteId, "");
		handlePageRes(model,request);
		return shiftMaintenanceUrl;
	}
	
	private void getShiftUserBindData(Model model, String siteId, String shiftId) {
		// 1.已分配班次的用戶列表
		// 查询班次的用戶信息
		List<UserFormMap> listSelectedUserFormMap = new ArrayList<UserFormMap>();
		if (!StringUtils.isEmpty(shiftId)) {
			UserShiftFormMap userShiftFormMap = new UserShiftFormMap();
			userShiftFormMap.put("shift_id", shiftId);
			userShiftFormMap.put("orderby", " order by create_time ");
			List<UserShiftFormMap> listUserShiftFormMap = new ArrayList<>();
			listUserShiftFormMap = baseMapper.findByNames(userShiftFormMap);

			// 如果有用户，再查询用户的详细信息
			if (ListUtils.isNotNull(listUserShiftFormMap)) {
				for (int i = 0; i < listUserShiftFormMap.size(); i++) {
					UserShiftFormMap map = listUserShiftFormMap.get(i);
					String userId = map.getStr("user_id");
					List<UserFormMap> listUserFormMap = baseMapper.findByAttribute("id", userId,UserFormMap.class);
					if (!ListUtils.isNotNull(listUserFormMap)) {
						String errMsg = "未查询到用户ID" + userId + "的详细信息，请确定该信息是否错误或被删除！";
						log.error(errMsg);
						model.addAttribute("errorMessage", errMsg);
					}
					listSelectedUserFormMap.add(listUserFormMap.get(0));
				}
			}
		}

		// 2.未分配班次的用户列表
		UserFormMap userFormMap2 = new UserFormMap();
		userFormMap2.put("where", " where site_id ='" + siteId + "'  order by create_time");
		List<UserFormMap> listAllUserFormMap = baseMapper.findByWhere(userFormMap2);
		UserShiftFormMap userShiftFormMap = new UserShiftFormMap();
		userShiftFormMap.put("where", " where site_id ='" + siteId + "' ");
		List<UserShiftFormMap> listAllUserShiftFormMap = baseMapper.findByWhere(userShiftFormMap);
		// 已被分配班次的用户列表
		List<String> listHasShiftUserId = new ArrayList<String>();
		for (int i = 0; i < listAllUserShiftFormMap.size(); i++) {
			UserShiftFormMap map = listAllUserShiftFormMap.get(i);
			String userId = map.getStr("user_id");
			listHasShiftUserId.add(userId);
		}
		List<UserFormMap> listUnSelectedUserFormMap = new ArrayList<UserFormMap>();
		for (int i = 0; i < listAllUserFormMap.size(); i++) {
			UserFormMap map = listAllUserFormMap.get(i);
			String id = map.getStr("id");
			if (!listHasShiftUserId.contains(id)) {
				listUnSelectedUserFormMap.add(map);
			}
		}

		model.addAttribute("unSelectedUserList", listUnSelectedUserFormMap);
		model.addAttribute("selectedUserList", listSelectedUserFormMap);
	}
	
	/**
	 * 保存班次信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveShift")
	@SystemLog(module="班次维护",methods="班次维护-保存班次")		//凡需要处理业务逻辑的.都需要记录操作日志
	public String saveShift() {
		ShiftFormMap shiftFormMap = getFormMap(ShiftFormMap.class);
		shiftFormMap.put("create_time", DateUtils.getStringDateTime());
		shiftFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		shiftFormMap.put("site_id", ShiroSecurityHelper.getSiteId());	
	
		try {
			shiftService.saveShift(shiftFormMap);	
		} catch (BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	

	/**
	 * 检索班次
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryShift")
	public String queryShift(Model model, HttpServletRequest request) {
		String siteId = ShiroSecurityHelper.getSiteId();
		String shiftNo = request.getParameter("shift_no");
		// 1.查询班次的基本信息
		ShiftFormMap shiftFormMap = new ShiftFormMap();
		shiftFormMap.put("shift_no", shiftNo);
		shiftFormMap.put("site_id", siteId);
		List<ShiftFormMap> listShiftFormMap = baseMapper.findByNames(shiftFormMap);
		if (!ListUtils.isNotNull(listShiftFormMap)) {
			String errMessage = "未检索到班次为：" + shiftNo.toUpperCase() + "的信息";
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
			model.addAttribute("errorMessage", errMessage);
			getShiftUserBindData(model, siteId, "");
			handlePageRes(model,request);
			return shiftMaintenanceUrl;
		}

		shiftFormMap = listShiftFormMap.get(0);
		model.addAttribute("shiftFormMap", shiftFormMap);

		String shiftId = shiftFormMap.getStr("id");
		// 2.查询班次的用户信息
		getShiftUserBindData(model, siteId, shiftId);
		
		//3.查询自定义数据
	    getUDefinedDataValue(model,shiftId,uDefinedDataType,"dataKeys");

		model.addAttribute("successMessage", "检索成功");
		handlePageRes(model,request);
		return shiftMaintenanceUrl;
	}
	
	/**
	 * 删除班次
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delShift")
	public String delNcCode(Model model, HttpServletRequest request) {
		String shiftId = request.getParameter("shift_id");
		try {
			if (StringUtils.isEmpty(shiftId)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			shiftService.delShift(shiftId);
		} catch (BusinessException e) {
			String errMessage = e.getMessage();
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
			model.addAttribute("errorMessage", errMessage);
			handlePageRes(model,request);
			return shiftMaintenanceUrl;
		}
		model.addAttribute("res", findByRes());
		model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
		model.addAttribute("successMessage", "删除班次成功");
		handlePageRes(model,request);
		return shiftMaintenanceUrl;
	}

}